package org.example.printexercise;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.widget.RelativeLayout;


public class WeChatPracticeActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText etInput;
    private Button btnSend;
    private TextView tvErrorCount;
    private LinearLayout inputLayout;

    private ChatAdapter chatAdapter;
    private List<ChatMessage> messageList;

    private List<String> practiceTexts;
    private String currentPracticeText;
    private int totalErrorCount = 0;
    private boolean isKeyboardVisible = false;
    private int keyboardHeight = 0;
    private boolean isFirstKeyboardShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wechat_practice);

        initViews();
        initData();
        setupRecyclerView();
        setupKeyboardListener();
        startNewRound();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.rv_chat);
        etInput = findViewById(R.id.et_input);
        btnSend = findViewById(R.id.btn_send);
        tvErrorCount = findViewById(R.id.tv_error_count);
        inputLayout = findViewById(R.id.input_layout);

        btnSend.setOnClickListener(v -> sendMessage());

        etInput.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == android.view.KeyEvent.ACTION_DOWN &&
                    keyCode == android.view.KeyEvent.KEYCODE_ENTER) {
                sendMessage();
                return true;
            }
            return false;
        });
    }

    // 在 WeChatPracticeActivity.java 中修改 initData() 方法
    private void initData() {
        messageList = new ArrayList<>();

        // 从 ImportArticleActivity 获取启用的微信对话内容
        String wechatContent = ImportArticleActivity.getEnabledArticleContent(this, ImportArticleActivity.ArticleMode.WECHAT_DIALOG.getModeId());

        // 如果有启用的文章内容，则使用该内容
        if (!wechatContent.equals("当前模式未创建文章，请前往导入文章页面导入文章")) {
            // 将文章内容按行分割为多个对话
            String[] lines = wechatContent.split("\n");
            practiceTexts = new ArrayList<>();
            for (String line : lines) {
                if (!line.trim().isEmpty()) {
                    practiceTexts.add(line.trim());
                }
            }
        } else {
            // 如果没有启用的文章，使用默认内容
            practiceTexts = Arrays.asList(
                    "领导，你们好，我们现在在去机场的路上，请您出口稍等一下，我们马上到",
                    "您好，请问这个产品的价格是多少？有没有优惠活动？",
                    "明天上午九点在公司会议室开会，请大家准时参加不要迟到",
                    "这个项目的进度需要加快，请各部门配合完成相应任务",
                    "周末的团建活动安排在森林公园，请大家带上运动装备",

                    // 工作沟通类
                    "关于上周讨论的方案，我已经完成了初步的设计文档",
                    "请把会议纪要发给所有参会人员，并跟进后续工作安排",
                    "这个月的销售数据已经出来了，比上个月增长了百分之十五",
                    "新版本的产品说明书已经更新，请查看附件中的详细内容",
                    "由于天气原因，原定于今天的户外活动改为室内进行",

                    // 客户服务类
                    "感谢您选择我们的产品，如有任何问题请随时联系我们",
                    "您的订单已经发货，预计明天下午可以送达",
                    "关于您反馈的问题，我们的技术团队正在紧急处理中",
                    "本次优惠活动截止到本月底，欢迎您抓紧时间参与",
                    "为了更好地为您服务，请提供一下您的订单编号",

                    // 会议安排类
                    "下周三下午两点在301会议室召开项目进度汇报会",
                    "请各位提前准备好汇报材料，每人发言时间十分钟",
                    "会议议程已经发到各位邮箱，请查收并确认",
                    "由于主持人临时有事，会议推迟到明天同一时间",
                    "会议录音和纪要稍后会整理发送给大家",

                    // 团队协作类
                    "这个任务需要市场部和技术部共同配合完成",
                    "请大家在下班前提交本周的工作总结报告",
                    "新员工培训安排在周一下午，请相关人员准时参加",
                    "为了项目顺利进行，我们需要增加两名开发人员",
                    "团队建设活动希望大家都能积极参与，增强凝聚力",

                    // 邮件写作类
                    "附件是您需要的项目资料，请查收",
                    "很高兴收到您的来信，关于您提出的建议我们会认真考虑",
                    "按照您的要求，我已经修改了方案中的相关部分",
                    "期待您的回复，如有任何问题请随时与我联系",
                    "感谢您的合作，希望我们今后有更多的合作机会",

                    // 商务谈判类
                    "关于价格方面，我们还可以再协商，希望能达成合作",
                    "这个报价已经是我们能给到的最优惠价格了",
                    "如果批量采购的话，我们可以提供额外的折扣",
                    "产品质量您完全可以放心，我们有多年的生产经验",
                    "合作细节我们可以进一步讨论，争取找到双方都满意的方案",

                    // 日常办公类
                    "打印机出现故障，已经联系维修人员，预计下午能修好",
                    "办公室的空调温度调得太低，建议调到二十六度",
                    "下周的值班表已经排好，请大家查看公告栏",
                    "公司网络明天上午九点到十点进行维护，期间可能无法上网",
                    "请大家节约用电，下班时记得关闭电脑和空调",

                    // 学习交流类
                    "关于这个技术问题，我建议参考官方文档的第三章",
                    "学习编程最重要的是多动手实践，理论结合实践",
                    "这个算法的复杂度是O(nlogn)，效率还是比较高的",
                    "论文的参考文献需要按照规范格式进行排版",
                    "小组讨论定在图书馆三楼，请大家带上相关资料",

                    // 项目管理类
                    "项目第一阶段已经完成，下周开始进入测试阶段",
                    "风险控制方案需要进一步完善，确保项目顺利进行",
                    "项目预算需要重新审核，有些开支超出了预期",
                    "关键路径上的任务要优先安排，不能有任何延误",
                    "项目总结报告需要包含成功经验和改进建议",

                    // 技术支持类
                    "请检查网络连接是否正常，重启路由器试试",
                    "软件更新到最新版本可以解决大部分兼容性问题",
                    "系统备份很重要，建议每周进行一次完整备份",
                    "这个错误代码表示内存不足，需要清理缓存",
                    "技术支持热线是400-123-4567，工作时间随时可以拨打"
            );
        }
    }


    private void setupRecyclerView() {
        chatAdapter = new ChatAdapter(messageList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(chatAdapter);
    }

    private void setupKeyboardListener() {
        final View activityRootView = getWindow().getDecorView();
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = activityRootView.getRootView().getHeight();
                int newKeyboardHeight = screenHeight - r.bottom;

                // 检测键盘状态变化
                if (newKeyboardHeight > screenHeight * 0.15) {
                    if (!isKeyboardVisible) {
                        isKeyboardVisible = true;
                        keyboardHeight = newKeyboardHeight;
                        if (isFirstKeyboardShow) {
                            isFirstKeyboardShow = false;
                            // 第一次键盘显示，延迟处理以确保布局已完成调整
                            recyclerView.postDelayed(() -> {
                                adjustInputLayoutForKeyboard(true);
                                adjustScrollForKeyboard();
                            }, 300);
                        } else {
                            adjustInputLayoutForKeyboard(true);
                            adjustScrollForKeyboard();
                        }
                    }
                } else {
                    if (isKeyboardVisible) {
                        isKeyboardVisible = false;
                        keyboardHeight = 0;
                        adjustInputLayoutForKeyboard(false);
                        adjustScrollForKeyboardHidden();
                    }
                }
            }
        });
    }

    private void adjustInputLayoutForKeyboard(boolean isKeyboardVisible) {
        if (isKeyboardVisible) {
            // 使用 RelativeLayout.LayoutParams 而不是 LinearLayout.LayoutParams
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) inputLayout.getLayoutParams();
            params.bottomMargin = keyboardHeight;
            inputLayout.setLayoutParams(params);
        } else {
            // 重置输入区域的位置
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) inputLayout.getLayoutParams();
            params.bottomMargin = 0;
            inputLayout.setLayoutParams(params);
        }
    }

    private void adjustScrollForKeyboard() {
        if (chatAdapter.getItemCount() == 0) return;

        recyclerView.post(() -> {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (layoutManager == null) return;

            int lastPosition = chatAdapter.getItemCount() - 1;
            View lastChild = layoutManager.findViewByPosition(lastPosition);

            if (lastChild == null) {
                layoutManager.scrollToPosition(lastPosition);
                return;
            }

            // 计算最后一条消息底部到RecyclerView底部的距离
            int lastChildBottom = lastChild.getBottom();
            int recyclerViewHeight = recyclerView.getHeight();
            int recyclerViewBottom = recyclerViewHeight - recyclerView.getPaddingBottom();

            int currentSpacing = recyclerViewBottom - lastChildBottom;
            int minSpacing = dpToPx(15);

            // 只有当间距小于15dp时才滚动
            if (currentSpacing < minSpacing) {
                int scrollDistance = minSpacing - currentSpacing;
                layoutManager.scrollToPositionWithOffset(lastPosition, -scrollDistance);
            }
            // 否则保持当前位置不变
        });
    }

    private void adjustScrollForKeyboardHidden() {
        if (chatAdapter.getItemCount() == 0) return;

        recyclerView.post(() -> {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (layoutManager == null) return;

            // 键盘隐藏时，确保从顶部开始显示
            layoutManager.scrollToPositionWithOffset(0, 0);
        });
    }

    private void adjustScrollForNewMessage() {
        if (chatAdapter.getItemCount() == 0) return;

        recyclerView.post(() -> {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (layoutManager == null) return;

            if (isKeyboardVisible) {
                // 键盘显示时，确保最后一条消息可见且有最小间距
                int lastPosition = chatAdapter.getItemCount() - 1;
                View lastChild = layoutManager.findViewByPosition(lastPosition);

                if (lastChild != null) {
                    int lastChildBottom = lastChild.getBottom();
                    int recyclerViewHeight = recyclerView.getHeight();
                    int recyclerViewBottom = recyclerViewHeight - recyclerView.getPaddingBottom();
                    int currentSpacing = recyclerViewBottom - lastChildBottom;
                    int minSpacing = dpToPx(15);

                    if (currentSpacing < minSpacing) {
                        int scrollDistance = minSpacing - currentSpacing;
                        layoutManager.scrollToPositionWithOffset(lastPosition, -scrollDistance);
                    }
                } else {
                    layoutManager.scrollToPosition(lastPosition);
                }
            } else {
                // 键盘隐藏时，从顶部开始显示
                layoutManager.scrollToPositionWithOffset(0, 0);
            }
        });
    }

    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp,
                getResources().getDisplayMetrics()
        );
    }

    private void startNewRound() {
        Random random = new Random();
        currentPracticeText = practiceTexts.get(random.nextInt(practiceTexts.size()));

        ChatMessage otherMessage = new ChatMessage(ChatMessage.TYPE_OTHER, currentPracticeText);
        chatAdapter.addMessage(otherMessage);

        recyclerView.postDelayed(this::adjustScrollForNewMessage, 100);
    }

    private void sendMessage() {
        String inputText = etInput.getText().toString().trim();
        if (TextUtils.isEmpty(inputText)) {
            return;
        }

        TextComparator.CompareResult result = TextComparator.compareText(currentPracticeText, inputText);
        int currentErrorCount = result.getErrorCount();
        totalErrorCount += currentErrorCount;

        ChatMessage myMessage = new ChatMessage(ChatMessage.TYPE_ME, inputText, result.getColoredText(), currentErrorCount);
        chatAdapter.addMessage(myMessage);

        etInput.setText("");
        updateErrorCount();
        adjustScrollForNewMessage();

        recyclerView.postDelayed(() -> {
            if (currentErrorCount <= 1) {
                startNewRound();
            } else {
                ChatMessage retryMessage = new ChatMessage(ChatMessage.TYPE_OTHER, currentPracticeText);
                chatAdapter.addMessage(retryMessage);
                adjustScrollForNewMessage();
            }
        }, 500);
    }

    private void updateErrorCount() {
        tvErrorCount.setText("错误: " + totalErrorCount);
    }

    @Override
    protected void onResume() {
        super.onResume();
        recyclerView.postDelayed(this::adjustScrollForNewMessage, 200);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isKeyboardVisible = false;
        keyboardHeight = 0;
        isFirstKeyboardShow = true;
        // 重置输入区域位置
        adjustInputLayoutForKeyboard(false);
    }
}
